import { Controller, Get, Post, Put, Del, Query, Body, Inject, Files, File } from '@midwayjs/core';
import { KnowledgeService } from '../service/knowledge.service';
import { ExcalidrawService } from '../service/excalidraw.service';
import { IKnowledgeCreateOptions, IKnowledgeUpdateOptions } from '../interface/knowledge.interface';
import { IExcalidrawAttachCreateOptions } from '../interface/excalidraw.interface';
import * as fs from 'fs';
import * as path from 'path';
import { v4 as uuidv4 } from 'uuid';

/**
 * 知识库控制器
 * 提供知识库的CRUD操作API接口
 */
@Controller('/api/knowledge')
export class KnowledgeController {
  @Inject()
  knowledgeService: KnowledgeService;
  
  @Inject()
  excalidrawService: ExcalidrawService;

  /**
   * 获取知识库列表
   * GET /api/knowledge/list
   * @returns 知识库列表
   */
  @Get('/list')
  async getKnowledgeList() {
    try {
      const knowledgeList = await this.knowledgeService.getKnowledgeList();
      
      return {
        success: true,
        message: '获取知识库列表成功',
        data: knowledgeList
      };
    } catch (error) {
      console.error('获取知识库列表错误:', error);
      
      return {
        success: false,
        message: '获取知识库列表失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 搜索知识库
   * GET /api/knowledge/search?name=xxx
   * @param name 知识库名称（模糊搜索）
   * @returns 搜索结果
   */
  @Get('/search')
  async searchKnowledge(@Query('name') name: string) {
    try {
      const knowledgeList = await this.knowledgeService.getKnowledgeByOptions({ name });
      
      return {
        success: true,
        message: '搜索知识库成功',
        data: knowledgeList
      };
    } catch (error) {
      console.error('搜索知识库错误:', error);
      
      return {
        success: false,
        message: '搜索知识库失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 搜索相关笔记
   * GET /api/knowledge/searchRelated?query=xxx
   * @param query 查询关键词
   * @returns 相关笔记列表
   */
  @Get('/searchRelated')
  async searchRelatedNotes(@Query('query') query: string) {
    try {
      const relatedNotes = await this.knowledgeService.searchRelatedNotes(query);
      
      return {
        success: true,
        message: '搜索相关笔记成功',
        data: relatedNotes
      };
    } catch (error) {
      console.error('搜索相关笔记错误:', error);
      
      return {
        success: false,
        message: '搜索相关笔记失败',
        data: [],
        error: error.message
      };
    }
  }

  /**
   * 获取单个知识库详情
   * GET /api/knowledge/detail?id=xxx
   * @param id 知识库ID
   * @returns 知识库详情
   */
  @Get('/detail')
  async getKnowledgeDetail(@Query('id') id: number) {
    // 参数验证
    if (!id || isNaN(Number(id))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      const knowledge = await this.knowledgeService.getKnowledgeById(Number(id));
      
      if (!knowledge) {
        return {
          success: false,
          message: '知识库不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '获取知识库详情成功',
        data: knowledge
      };
    } catch (error) {
      console.error('获取知识库详情错误:', error);
      
      return {
        success: false,
        message: '获取知识库详情失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 创建知识库
   * POST /api/knowledge/create
   * @param options 创建参数
   * @returns 创建结果
   */
  @Post('/create')
  async createKnowledge(@Body() options: IKnowledgeCreateOptions) {
    // 参数验证
    if (!options.name || !options.name.trim()) {
      return {
        success: false,
        message: '知识库名称不能为空',
        data: null
      };
    }

    // if (!options.content || !options.content.trim()) {
    //   return {
    //     success: false,
    //     message: '知识库内容不能为空',
    //     data: null
    //   };
    // }

    try {
      const knowledgeId = await this.knowledgeService.createKnowledge(
        {
          name: options.name.trim(),
          content: options.content.trim(),
          excalidraw: options.excalidraw // 添加Excalidraw数据
        },
        options.tags
      );
      
      return {
        success: true,
        message: '创建知识库成功',
        data: {
          id: knowledgeId
        }
      };
    } catch (error) {
      console.error('创建知识库错误:', error);
      
      return {
        success: false,
        message: '创建知识库失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 更新知识库
   * PUT /api/knowledge/update
   * @param options 更新参数
   * @returns 更新结果
   */
  @Post('/update')
  async updateKnowledge(@Body() options: IKnowledgeUpdateOptions) {
    // 参数验证
    if (!options.id || isNaN(Number(options.id))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      const success = await this.knowledgeService.updateKnowledge(
        {
          id: Number(options.id),
          name: options.name,
          content: options.content,
          excalidraw: options.excalidraw // 添加Excalidraw数据
        },
        options.tags
      );
      
      if (!success) {
        return {
          success: false,
          message: '知识库不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '更新知识库成功',
        data: null
      };
    } catch (error) {
      console.error('更新知识库错误:', error);
      
      return {
        success: false,
        message: '更新知识库失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 删除知识库
   * DELETE /api/knowledge/delete?id=xxx
   * @param id 知识库ID
   * @returns 删除结果
   */
  @Del('/delete')
  async deleteKnowledge(@Query('id') id: number) {
    // 参数验证
    if (!id || isNaN(Number(id))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      const success = await this.knowledgeService.deleteKnowledge(Number(id));
      
      if (!success) {
        return {
          success: false,
          message: '知识库不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '删除知识库成功',
        data: null
      };
    } catch (error) {
      console.error('删除知识库错误:', error);
      
      return {
        success: false,
        message: '删除知识库失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 保存知识库的Excalidraw数据
   * PUT /api/knowledge/saveExcalidraw
   * @param options 包含知识库ID和Excalidraw数据的对象
   * @returns 保存结果
   */
  @Put('/saveExcalidraw')
  async saveKnowledgeExcalidraw(@Body() options: { id: number, excalidraw: string }) {
    // 参数验证
    if (!options.id || isNaN(Number(options.id))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    if (!options.excalidraw) {
      return {
        success: false,
        message: 'Excalidraw数据不能为空',
        data: null
      };
    }

    try {
      const success = await this.knowledgeService.updateKnowledge({
        id: Number(options.id),
        excalidraw: options.excalidraw
      });
      
      if (!success) {
        return {
          success: false,
          message: '知识库不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '保存Excalidraw数据成功',
        data: null
      };
    } catch (error) {
      console.error('保存Excalidraw数据错误:', error);
      
      return {
        success: false,
        message: '保存Excalidraw数据失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 获取知识库的Excalidraw数据
   * GET /api/knowledge/getExcalidraw?id=xxx
   * @param id 知识库ID
   * @returns Excalidraw数据
   */
  @Get('/getExcalidraw')
  async getKnowledgeExcalidraw(@Query('id') id: number) {
    // 参数验证
    if (!id || isNaN(Number(id))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      const knowledge = await this.knowledgeService.getKnowledgeById(Number(id));
      
      if (!knowledge) {
        return {
          success: false,
          message: '知识库不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '获取Excalidraw数据成功',
        data: {
          excalidraw: knowledge.excalidraw || null
        }
      };
    } catch (error) {
      console.error('获取Excalidraw数据错误:', error);
      
      return {
        success: false,
        message: '获取Excalidraw数据失败',
        data: null,
        error: error.message
      };
    }
  }
  
  /**
   * 上传Excalidraw附件
   * POST /api/knowledge/uploadExcalidrawAttachment
   * @param file 上传的文件
   * @param knowledgeId 知识库ID
   * @returns 上传结果
   */
  @Post('/uploadExcalidrawAttachment')
  async uploadExcalidrawAttachment(@File() file, @Body() body: { knowledgeId: number }) {
    // 参数验证
    if (!file) {
      return {
        success: false,
        message: '请上传文件',
        data: null
      };
    }

    if (!body.knowledgeId || isNaN(Number(body.knowledgeId))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      // 确保存储目录存在
      const staticDir = path.join(process.cwd(), 'public', 'excalidraw');
      if (!fs.existsSync(staticDir)) {
        fs.mkdirSync(staticDir, { recursive: true });
      }
      
      // 生成唯一文件名
      const fileExt = path.extname(file.filename);
      const fileName = `${uuidv4()}${fileExt}`;
      const filePath = path.join(staticDir, fileName);
      
      // 保存文件
      fs.writeFileSync(filePath, file.data);
      
      // 构建URL路径
      const fileUrl = `/public/excalidraw/${fileName}`;
      
      // 保存到数据库
      const options: IExcalidrawAttachCreateOptions = {
        knowledge_id: Number(body.knowledgeId),
        excalidraw_json_url: fileUrl,
        image_url: null
      };
      
      const id = await this.excalidrawService.createExcalidrawAttach(options);
      
      return {
        success: true,
        message: '上传附件成功',
        data: {
          id,
          url: fileUrl
        }
      };
    } catch (error) {
      console.error('上传附件错误:', error);
      
      return {
        success: false,
        message: '上传附件失败',
        data: null,
        error: error.message
      };
    }
  }
  
  /**
   * 获取知识库的Excalidraw附件列表
   * GET /api/knowledge/getExcalidrawAttachments?knowledgeId=xxx
   * @param knowledgeId 知识库ID
   * @returns 附件列表
   */
  @Get('/getExcalidrawAttachments')
  async getExcalidrawAttachments(@Query('knowledgeId') knowledgeId: number) {
    // 参数验证
    if (!knowledgeId || isNaN(Number(knowledgeId))) {
      return {
        success: false,
        message: '请提供有效的知识库ID',
        data: null
      };
    }

    try {
      const attachments = await this.excalidrawService.getExcalidrawAttachByKnowledgeId(Number(knowledgeId));
      
      return {
        success: true,
        message: '获取附件列表成功',
        data: attachments
      };
    } catch (error) {
      console.error('获取附件列表错误:', error);
      
      return {
        success: false,
        message: '获取附件列表失败',
        data: null,
        error: error.message
      };
    }
  }
  
  /**
   * 删除Excalidraw附件
   * DELETE /api/knowledge/deleteExcalidrawAttachment?attachmentId=xxx
   * @param attachmentId 附件ID
   * @returns 删除结果
   */
  @Del('/deleteExcalidrawAttachment')
  async deleteExcalidrawAttachment(@Query('attachmentId') attachmentId: number) {
    // 参数验证
    if (!attachmentId || isNaN(Number(attachmentId))) {
      return {
        success: false,
        message: '请提供有效的附件ID',
        data: null
      };
    }

    try {
      const success = await this.excalidrawService.deleteExcalidrawAttach(Number(attachmentId));
      
      if (!success) {
        return {
          success: false,
          message: '附件不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '删除附件成功',
        data: null
      };
    } catch (error) {
      console.error('删除附件错误:', error);
      
      return {
        success: false,
        message: '删除附件失败',
        data: null,
        error: error.message
      };
    }
  }

  /**
   * 删除知识库标签
   * DELETE /api/knowledge/deleteTag?tagId=xxx
   * @param tagId 标签ID
   * @returns 删除结果
   */
  @Del('/deleteTag')
  async deleteKnowledgeTag(@Query('tagId') tagId: number) {
    // 参数验证
    if (!tagId || isNaN(Number(tagId))) {
      return {
        success: false,
        message: '请提供有效的标签ID',
        data: null
      };
    }

    try {
      const success = await this.knowledgeService.deleteKnowledgeTag(Number(tagId));
      
      if (!success) {
        return {
          success: false,
          message: '标签不存在',
          data: null
        };
      }
      
      return {
        success: true,
        message: '删除标签成功',
        data: null
      };
    } catch (error) {
      console.error('删除标签错误:', error);
      
      return {
        success: false,
        message: '删除标签失败',
        data: null,
        error: error.message
      };
    }
  }
}